package handler

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"user_5.24/api/request"
	"user_5.24/internal/dao"
	"user_5.24/internal/model"
)

func GoodsAdd(c *gin.Context) {
	var req request.Add
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	result := dao.Create(&model.Goods{
		Title:  req.Title,
		Price:  req.Price,
		Stock:  req.Stock,
		UserId: c.GetUint("userId"),
	})
	if !result {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "商品添加失败",
			"data": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "商品添加成功",
		"data": true,
	})

}

func Update(c *gin.Context) {
	var req request.Update
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var goods model.Goods
	dao.GetOneById(req.Id, &goods)
	if goods.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "当前商品未存在",
			"data": nil,
		})
		return
	}
	result := dao.Update(&model.Goods{
		Id:    req.Id,
		Title: req.Title,
		Price: req.Price,
		Stock: req.Stock,
	})

	if !result {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "商品修改失败",
			"data": false,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "商品修改成功",
		"data": true,
	})
}

func List(c *gin.Context) {
	var req request.List
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	var goods []model.Goods
	dao.GetListByFields(&model.Goods{
		Id:     req.Id,
		UserId: req.UserId,
		Title:  req.Title,
	}, &goods)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "商品列表展示成功",
		"data": goods,
	})

}

func Page(c *gin.Context) {
	var req request.Page
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 10000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}
	pageDto := dao.PageDto{
		Page:     req.Page,
		PageSize: req.PageSize,
		OrderBy:  "created_at desc",
	}
	var goods []model.Goods
	paginate, _ := dao.Paginate(&model.Goods{
		Id:     req.Id,
		UserId: req.UserId,
		Title:  req.Title,
	}, pageDto, &goods)

	c.JSON(http.StatusOK, gin.H{
		"code": http.StatusOK,
		"msg":  "成功",
		"data": paginate,
	})
	
}
